package com.yubao.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yubao.request.*;
import com.yubao.response.AnswerViewModel;
import com.yubao.response.PageObject;
import com.yubao.response.QuestionViewModel;
import com.yubao.mapper.AnswerMapper;
import com.yubao.mapper.QuestionMapper;
import com.yubao.mapper.UserMapper;
import com.yubao.entity.*;

import com.yubao.response.UserViewModel;
import com.yubao.util.NormalException;
import org.assertj.core.util.Strings;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * Created by Administrator on 2016-12-01.
 */
@Service
public class QuestionService extends ServiceImpl<QuestionMapper, Question> implements IService<Question> {

	@Autowired
    QuestionMapper _mapper;

	@Autowired
    LoginService loginService;

	@Autowired
    AnswerMapper _answerMapper;
	@Autowired
    UserMapper _userMapper;

	@Autowired
    MessageService _msgService;

    DozerBeanMapper mapper = new DozerBeanMapper();

        public PageObject<QuestionViewModel> queryList(QuestionListReq req) {
            int index = req.getIndex();
            int size = req.getSize();
            String type = req.getType();
            String key = req.getKey();
        if(index == 0) index = 1;
        if(size ==0) size = 10;
        if(type == null) type="";

        QuestionExample exp = new QuestionExample();
        exp.setOrderByClause("stick desc,time desc");

        QuestionExample.Criteria criteria = exp.createCriteria();

        if(key != null && !key.equals(""))
        {
            criteria.andTitleLike(key);
        }

        if (type.equals("resolved")) {  //已解决
            criteria.andAcceptIsNotNull();
        } else if (type.equals("unresolved")) {  //未解决
            criteria.andAcceptIsNull();
        } else if (type.equals("wonderful")) {    //精帖
            criteria.andStatusGreaterThan(0);
        }

        PageObject<QuestionViewModel> obj = new PageObject<QuestionViewModel>();
        obj.setSize(size);

        obj.setTotal(_mapper.countByExample(exp));

        int startindex = (index-1)*size;
        exp.setOffset(startindex);
        exp.setLimit(size);


        obj.setObjects(_mapper.getQuestionVMs(exp));

        return obj;
    }

    public String add(AddQuestionReq req) throws Exception {
       UserViewModel user = checkLogin();
        String id = UUID.randomUUID().toString();
        Question question = mapper.map(req, Question.class);
        question.setUserid(user.getId());
        question.setTime(new Date());
        question.setId(id);
        save(question);
        return id;
    }

    public String edit(AddQuestionReq req) throws Exception {

        UserViewModel loginInfo = checkLogin();
        Question question = mapper.map(req, Question.class);
        saveOrUpdate(question);
        return question.getId();
    }

    public void del(String id) throws Exception {
       UserViewModel user = checkLogin();
        if(user.getAuth() != 1)
        {
            throw new Exception("哇偶！快联系站长删除");
        }
        removeById(id);
    }

    public void set(String id, String field, int rank) throws Exception {
       UserViewModel user = checkLogin();
        if(user.getAuth() != 1 && user.getAuth() != 2)
        {
            throw new Exception("哇偶！这是站长那帮人干的事");
        }

        QuestionExample exp = new QuestionExample();
        QuestionExample.Criteria criteria = exp.createCriteria();
        criteria.andIdEqualTo(id);

        Question question = getById(id);

        if(field.equals("stick"))  //置顶
        {
            question.setStick(rank);
        }
        else if(field.equals("status")) //精贴
        {
            question.setStatus(rank);
        }
        _mapper.updateByExampleSelective(question, exp);

    }

    public void delAnswer(String id) throws Exception {
       UserViewModel user = checkLogin();
        if(user.getAuth() != 1)
        {
            throw new Exception("哇偶！快联系站长删除");
        }

        _answerMapper.deleteById(id);
    }

    public void accept(String id) throws Exception {
       UserViewModel loginuser = checkLogin();
        Answer answer = _answerMapper.selectById(id);

        if(loginuser.getAuth() != 1 &&loginuser.getAuth()!= 2 && answer.getUserId() == loginuser.getId() )
        {
            throw new Exception("哇偶！你无权干涉这个问题");
        }

        Question question = getById(answer.getAnswerTo());
        question.setAccept(answer.getId());
        updateById(question);

        User user = _userMapper.selectById(loginuser.getId());
        user.setExperience(loginuser.getExperience() + question.getExperience());
        _userMapper.updateById(user);
    }

    public PageObject<QuestionViewModel> getbyuser(QueryQuestionsByUser request) {
            int index = request.getIndex(), size = request.getSize();
        if(index == 0) index = 1;
        if(size ==0) size = 10;

        QuestionExample exp = new QuestionExample();
        exp.setOrderByClause("time desc");

        QuestionExample.Criteria criteria = exp.createCriteria();
        criteria.andUseridEqualTo(request.getUid());

        PageObject<QuestionViewModel> obj = new PageObject<QuestionViewModel>();
        obj.setSize(size);

        obj.setTotal(_mapper.countByExample(exp));

        int startindex = (index-1)*size;
        exp.setOffset(startindex);
        exp.setLimit(size);


        obj.setObjects(_mapper.getQuestionVMs(exp));

        return obj;
    }

    //获取用户回答过的问题列表
        public PageObject<QuestionViewModel> getByUserAnswer(QueryQuestionsByUser req) {

        PageObject<QuestionViewModel> obj = new PageObject<QuestionViewModel>();
        Page<QuestionViewModel> questionPage = _mapper.getUserAnswered(
                new Page<QuestionViewModel>(req.getIndex(), req.getSize()),req.getUid());

        obj.setSize(req.getSize());
        obj.setTotal((int) questionPage.getTotal());
        obj.setObjects(questionPage.getRecords());

        return obj;
    }

    //获取某个具体问题的回答
    public PageObject<AnswerViewModel> queryAnswersOfQuestion(QueryAnswersOfQuestionReq req) throws NormalException {
        if(Strings.isNullOrEmpty(req.getJid())){
            throw new NormalException("问题ID不能为空");
        }
        PageObject<AnswerViewModel> resp = new PageObject<AnswerViewModel>();
        Page<AnswerViewModel> questionPage = _answerMapper.queryAnswersOfQuestion(new Page<AnswerViewModel>(req.getIndex(), req.getSize()),req.getJid());

        resp.setSize(req.getSize());
        resp.setTotal((int) questionPage.getTotal());
        resp.setObjects(questionPage.getRecords());

        return resp;
    }

    public PageObject<QuestionViewModel> getHot() {
            int index = 1;
            int size = 10;
        QuestionExample exp = new QuestionExample();
        exp.setOrderByClause("hits desc,time desc");

        PageObject<QuestionViewModel> obj = new PageObject<QuestionViewModel>();
        obj.setSize(size);

        obj.setTotal(_mapper.countByExample(exp));

        int startindex = (index-1)*size;
        exp.setOffset(startindex);
        exp.setLimit(size);


        obj.setObjects(_mapper.getQuestionVMs(exp));

        return obj;
    }

    public String addAnswer(AddAnswerRequest request) throws Exception {
       UserViewModel loginUser = checkLogin();
        String id = addAnswer(request.getJid(), request.getContent(), loginUser);

        User user = _userMapper.selectById(loginUser.getId());
        user.setAnswercnt(loginUser.getAnswercnt() + 1);
        _userMapper.updateById(user);

        QuestionExample exp = new QuestionExample();
        QuestionExample.Criteria criteria = exp.createCriteria();
        criteria.andIdEqualTo(request.getJid());

        Question question = getById(request.getJid());
        question.setComment(question.getComment() + 1);
        _mapper.updateByExampleSelective(question, exp);

        _msgService.notify(user, question);
        return id;

    }

    private String addAnswer(String jid, String content, UserViewModel user) {
        String id = UUID.randomUUID().toString();
        Answer answer = new Answer();
        answer.setId(id);
        answer.setUserId(user.getId());
        answer.setContent(content);
        answer.setAnswerTo(jid);
        answer.setTime(new Date());
        _answerMapper.insert(answer);
        return id;
    }




    public QuestionViewModel Get(String id) {
        QuestionViewModel q = _mapper.getQuestionVM(id);
        addHitCnt(id);
        return q;
    }


    private UserViewModel checkLogin() throws Exception {
        UserViewModel user = loginService.get();
        if(user == null){
            throw new Exception("请先登录");
        }
        return user;
    }

    private void addHitCnt(String id){
        QuestionExample exp = new QuestionExample();
        QuestionExample.Criteria criteria = exp.createCriteria();
        criteria.andIdEqualTo(id);

        Question question = getById(id);
        question.setHits(question.getHits() + 1);
        _mapper.updateByExampleSelective(question, exp);
    }


}
